<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>股票分析平台 - 集成仪表板</title>
    <script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        
        .header {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            padding: 1rem 2rem;
            box-shadow: 0 2px 20px rgba(0,0,0,0.1);
            position: sticky;
            top: 0;
            z-index: 1000;
        }
        
        .header-content {
            display: flex;
            justify-content: space-between;
            align-items: center;
            max-width: 1400px;
            margin: 0 auto;
        }
        
        .logo {
            font-size: 1.5rem;
            font-weight: bold;
            color: #333;
        }
        
        .user-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 2rem;
        }
        
        .dashboard-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 2rem;
            margin-bottom: 2rem;
        }
        
        .module-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 2rem;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }
        
        .module-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 40px rgba(0,0,0,0.15);
        }
        
        .module-header {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin-bottom: 1.5rem;
        }
        
        .module-icon {
            font-size: 2rem;
        }
        
        .module-title {
            font-size: 1.5rem;
            font-weight: bold;
            color: #333;
        }
        
        .module-description {
            color: #666;
            margin-bottom: 1.5rem;
            line-height: 1.6;
        }
        
        .btn {
            padding: 0.75rem 1.5rem;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 500;
            transition: all 0.3s ease;
            text-decoration: none;
            display: inline-block;
            text-align: center;
        }
        
        .btn-primary {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
        }
        
        .btn-success {
            background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            color: white;
        }
        
        .btn-success:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(79, 172, 254, 0.4);
        }
        
        .btn-warning {
            background: linear-gradient(135deg, #fa709a 0%, #fee140 100%);
            color: white;
        }
        
        .btn-warning:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(250, 112, 154, 0.4);
        }
        
        .status-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1rem;
            margin-top: 2rem;
        }
        
        .status-card {
            background: rgba(255, 255, 255, 0.9);
            padding: 1.5rem;
            border-radius: 10px;
            text-align: center;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .status-value {
            font-size: 2rem;
            font-weight: bold;
            color: #333;
        }
        
        .status-label {
            color: #666;
            margin-top: 0.5rem;
        }
        
        .realtime-panel {
            background: rgba(255, 255, 255, 0.95);
            border-radius: 15px;
            padding: 2rem;
            margin-top: 2rem;
            box-shadow: 0 8px 32px rgba(0,0,0,0.1);
        }
        
        .stock-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 1rem;
            margin-top: 1rem;
        }
        
        .stock-card {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            border-left: 4px solid #007bff;
            position: relative;
            transition: all 0.3s ease;
        }

        .stock-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }

        .stock-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 0.5rem;
        }

        .stock-code {
            font-weight: bold;
            color: #333;
            font-size: 1rem;
        }

        .stock-name {
            color: #666;
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }

        .stock-price {
            font-size: 1.4rem;
            font-weight: bold;
            margin: 0.5rem 0;
        }

        .stock-change {
            font-size: 0.9rem;
            margin-bottom: 0.5rem;
        }

        .stock-volume {
            font-size: 0.8rem;
            color: #999;
            margin-bottom: 0.3rem;
        }

        .stock-time {
            font-size: 0.7rem;
            color: #aaa;
        }

        .remove-btn {
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 50%;
            width: 24px;
            height: 24px;
            cursor: pointer;
            font-size: 14px;
            line-height: 1;
            transition: all 0.2s ease;
        }

        .remove-btn:hover {
            background: #c82333;
            transform: scale(1.1);
        }
        
        .price-up {
            color: #28a745;
        }
        
        .price-down {
            color: #dc3545;
        }
        
        .hidden {
            display: none;
        }
        
        .loading {
            text-align: center;
            color: #666;
            font-style: italic;
        }
        
        .error {
            color: #dc3545;
            background: #f8d7da;
            padding: 1rem;
            border-radius: 5px;
            margin: 1rem 0;
        }
        
        .success {
            color: #155724;
            background: #d4edda;
            padding: 1rem;
            border-radius: 5px;
            margin: 1rem 0;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
        }

        .modal.hidden {
            display: none;
        }

        .modal:not(.hidden) {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .modal-content {
            background-color: white;
            border-radius: 10px;
            width: 90%;
            max-width: 400px;
            box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
            animation: modalSlideIn 0.3s ease-out;
        }

        @keyframes modalSlideIn {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .modal-header {
            padding: 1.5rem;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h2 {
            margin: 0;
            color: #333;
        }

        .close {
            font-size: 28px;
            font-weight: bold;
            color: #aaa;
            cursor: pointer;
            line-height: 1;
        }

        .close:hover {
            color: #000;
        }

        .modal-body {
            padding: 1.5rem;
        }

        .form-group {
            margin-bottom: 1rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            color: #333;
            font-weight: 500;
        }

        .form-group input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid #ddd;
            border-radius: 5px;
            font-size: 1rem;
            box-sizing: border-box;
        }

        .form-group input:focus {
            outline: none;
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }

        .form-actions {
            display: flex;
            gap: 1rem;
            margin-top: 1.5rem;
        }

        .form-actions .btn {
            flex: 1;
        }

        .btn-secondary {
            background: #6c757d;
            color: white;
            border: none;
            padding: 0.75rem 1rem;
            border-radius: 5px;
            cursor: pointer;
            font-size: 0.9rem;
            transition: all 0.2s ease;
        }

        .btn-secondary:hover {
            background: #5a6268;
        }

        /* 用户管理样式 */
        .user-management-container {
            max-height: 70vh;
            overflow-y: auto;
        }

        .user-stats {
            margin-bottom: 1.5rem;
        }

        .stat-card {
            background: #f8f9fa;
            padding: 1rem;
            border-radius: 8px;
            text-align: center;
            border: 1px solid #dee2e6;
        }

        .stat-card h3 {
            margin: 0 0 0.5rem 0;
            color: #495057;
            font-size: 1.1rem;
        }

        .stat-card p {
            margin: 0;
            font-size: 1.5rem;
            font-weight: bold;
            color: #007bff;
        }

        .user-table-container {
            overflow-x: auto;
        }

        .user-table {
            width: 100%;
            border-collapse: collapse;
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }

        .user-table th,
        .user-table td {
            padding: 0.75rem;
            text-align: left;
            border-bottom: 1px solid #dee2e6;
        }

        .user-table th {
            background: #f8f9fa;
            font-weight: 600;
            color: #495057;
            font-size: 0.9rem;
        }

        .user-table tr:hover {
            background: #f8f9fa;
        }

        .status-badge {
            padding: 0.25rem 0.5rem;
            border-radius: 4px;
            font-size: 0.8rem;
            font-weight: 500;
        }

        .status-active {
            background: #d4edda;
            color: #155724;
        }

        .status-inactive {
            background: #f8d7da;
            color: #721c24;
        }

        .status-admin {
            background: #fff3cd;
            color: #856404;
        }

        .status-user {
            background: #d1ecf1;
            color: #0c5460;
        }

        .btn-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.8rem;
            margin: 0 0.2rem;
        }

        .btn-success {
            background: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-success:hover {
            background: #218838;
        }

        .btn-danger {
            background: #dc3545;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.2s ease;
        }

        .btn-danger:hover {
            background: #c82333;
        }
    </style>
</head>
<body>
    <div class="header">
        <div class="header-content">
            <div class="logo">📈 股票分析平台</div>
            <div class="user-info">
                <span id="userInfo">未登录</span>
                <button id="loginBtn" class="btn btn-primary" onclick="showAuthModal()">登录/注册</button>
                <button id="logoutBtn" class="btn btn-warning hidden" onclick="logout()">退出</button>
            </div>
        </div>
    </div>

    <div class="container">
        <h1 style="text-align: center; color: white; margin-bottom: 2rem; font-size: 2.5rem;">
            🚀 集成股票分析系统
        </h1>
        
        <div class="dashboard-grid">
            <!-- 测试一：财务数据分析 -->
            <div class="module-card">
                <div class="module-header">
                    <div class="module-icon">📊</div>
                    <div>
                        <div class="module-title">财务数据分析</div>
                        <div style="color: #28a745; font-weight: bold;">✅ 测试一</div>
                    </div>
                </div>
                <div class="module-description">
                    获取股票近6年财务报表，包括营业收入、净利润等关键指标，支持动态查询和图表展示。
                </div>
                <a href="/" class="btn btn-primary">进入财务分析</a>
            </div>

            <!-- 测试二：沪深大盘实时数据 -->
            <div class="module-card">
                <div class="module-header">
                    <div class="module-icon">📊</div>
                    <div>
                        <div class="module-title">沪深大盘实时数据</div>
                        <div style="color: #17a2b8; font-weight: bold;">📈 测试二</div>
                    </div>
                </div>
                <div class="module-description">
                    从网上获取沪深大盘实时价格数据，每隔3秒获取一次，保存到Redis，前端通过Redis获取数据并图表展示。
                </div>
                <a href="/market" class="btn btn-success">进入大盘监控</a>
            </div>

            <!-- 测试三：用户管理系统 -->
            <div class="module-card">
                <div class="module-header">
                    <div class="module-icon">👥</div>
                    <div>
                        <div class="module-title">用户管理系统</div>
                        <div style="color: #ffc107; font-weight: bold;">🔐 测试三</div>
                    </div>
                </div>
                <div class="module-description">
                    用户注册登录，JWT身份验证，权限管理，管理员后台功能。
                </div>
                <button class="btn btn-warning" onclick="showUserManagement()">用户管理</button>
            </div>

            <!-- 系统状态 -->
            <div class="module-card">
                <div class="module-header">
                    <div class="module-icon">⚡</div>
                    <div>
                        <div class="module-title">系统状态</div>
                        <div style="color: #6f42c1; font-weight: bold;">📊 监控</div>
                    </div>
                </div>
                <div class="module-description">
                    实时监控系统运行状态，包括API响应时间、数据库连接、Redis状态等。
                </div>
                <button class="btn btn-primary" onclick="refreshStatus()">刷新状态</button>
            </div>
        </div>

        <!-- 系统状态面板 -->
        <div class="status-grid">
            <div class="status-card">
                <div class="status-value" id="apiStatus">检查中...</div>
                <div class="status-label">API状态</div>
            </div>
            <div class="status-card">
                <div class="status-value" id="dbStatus">检查中...</div>
                <div class="status-label">数据库</div>
            </div>
            <div class="status-card">
                <div class="status-value" id="redisStatus">检查中...</div>
                <div class="status-label">Redis缓存</div>
            </div>
            <div class="status-card">
                <div class="status-value" id="wsStatus">检查中...</div>
                <div class="status-label">WebSocket</div>
            </div>
        </div>

        <!-- 实时监控控制按钮 -->
        <div style="text-align: center; margin: 2rem 0;">
            <button id="realtimeToggleBtn" class="btn btn-success" onclick="toggleRealtime()">
                📈 启动实时股价监控
            </button>
        </div>

        <!-- 实时股价面板 -->
        <div id="realtimePanel" class="realtime-panel hidden">
            <h3>📈 实时股价监控</h3>
            <div style="margin: 1rem 0;">
                <input type="text" id="stockInput" placeholder="输入股票代码 (如: 000001)" style="padding: 0.5rem; margin-right: 1rem; border: 1px solid #ddd; border-radius: 4px;" onkeypress="if(event.key==='Enter') addStock()">
                <button class="btn btn-primary" onclick="addStock()">添加监控</button>
                <button class="btn btn-warning" onclick="clearStocks()">清空</button>
            </div>

            <!-- 快速添加常用股票 -->
            <div style="margin: 1rem 0;">
                <span style="color: #666; margin-right: 1rem;">快速添加:</span>
                <button class="btn btn-sm" onclick="quickAddStock('000001')" style="margin: 0.2rem; padding: 0.3rem 0.6rem; font-size: 0.8rem;">000001 平安银行</button>
                <button class="btn btn-sm" onclick="quickAddStock('000002')" style="margin: 0.2rem; padding: 0.3rem 0.6rem; font-size: 0.8rem;">000002 万科A</button>
                <button class="btn btn-sm" onclick="quickAddStock('600519')" style="margin: 0.2rem; padding: 0.3rem 0.6rem; font-size: 0.8rem;">600519 贵州茅台</button>
                <button class="btn btn-sm" onclick="quickAddStock('002962')" style="margin: 0.2rem; padding: 0.3rem 0.6rem; font-size: 0.8rem;">002962 五方光电</button>
                <button class="btn btn-sm" onclick="quickAddStock('300750')" style="margin: 0.2rem; padding: 0.3rem 0.6rem; font-size: 0.8rem;">300750 宁德时代</button>
            </div>

            <div id="stockGrid" class="stock-grid"></div>
        </div>
    </div>

    <!-- 登录/注册模态框 -->
    <div id="authModal" class="modal hidden">
        <div class="modal-content">
            <div class="modal-header">
                <h2 id="modalTitle">用户登录</h2>
                <span class="close" onclick="closeAuthModal()">&times;</span>
            </div>
            <div class="modal-body">
                <form id="authForm">
                    <div class="form-group">
                        <label for="username">用户名:</label>
                        <input type="text" id="username" name="username" required>
                    </div>
                    <div class="form-group">
                        <label for="password">密码:</label>
                        <input type="password" id="password" name="password" required>
                    </div>
                    <div class="form-group" id="emailGroup" style="display: none;">
                        <label for="email">邮箱:</label>
                        <input type="email" id="email" name="email">
                    </div>
                    <div class="form-group" id="fullNameGroup" style="display: none;">
                        <label for="fullName">姓名:</label>
                        <input type="text" id="fullName" name="fullName">
                    </div>
                    <div class="form-actions">
                        <button type="submit" id="authSubmitBtn" class="btn btn-primary">登录</button>
                        <button type="button" id="toggleModeBtn" class="btn btn-secondary" onclick="toggleAuthMode()">
                            没有账号？点击注册
                        </button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 用户管理模态框 -->
    <div id="userManagementModal" class="modal" style="display: none;">
        <div class="modal-content" style="max-width: 1000px; width: 90%;">
            <div class="modal-header">
                <h2>用户管理</h2>
                <span class="close" onclick="closeUserManagement()">&times;</span>
            </div>
            <div class="modal-body">
                <div class="user-management-container">
                    <div class="user-stats">
                        <div class="stat-card">
                            <h3>用户统计</h3>
                            <p id="userCount">加载中...</p>
                        </div>
                    </div>

                    <div class="user-table-container">
                        <table class="user-table">
                            <thead>
                                <tr>
                                    <th>ID</th>
                                    <th>用户名</th>
                                    <th>邮箱</th>
                                    <th>姓名</th>
                                    <th>状态</th>
                                    <th>角色</th>
                                    <th>注册时间</th>
                                    <th>操作</th>
                                </tr>
                            </thead>
                            <tbody id="userTableBody">
                                <!-- 用户数据将在这里动态加载 -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script>
        let ws = null;
        let isRealtimeActive = false;
        let monitoredStocks = new Set();

        // 页面加载时检查登录状态和系统状态
        window.onload = function() {
            checkLoginStatus();
            refreshStatus();
        };

        // 检查登录状态
        function checkLoginStatus() {
            const token = localStorage.getItem('access_token');
            if (token) {
                // 验证token有效性
                fetch('/api/auth/me', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                })
                .then(response => {
                    if (response.ok) {
                        return response.json();
                    }
                    throw new Error('Token invalid');
                })
                .then(user => {
                    document.getElementById('userInfo').textContent = `欢迎, ${user.full_name || user.username}`;
                    document.getElementById('loginBtn').classList.add('hidden');
                    document.getElementById('logoutBtn').classList.remove('hidden');
                })
                .catch(() => {
                    localStorage.removeItem('access_token');
                });
            }
        }

        let isLoginMode = true;

        // 显示认证模态框
        function showAuthModal() {
            document.getElementById('authModal').classList.remove('hidden');
            setLoginMode();
        }

        // 关闭认证模态框
        function closeAuthModal() {
            document.getElementById('authModal').classList.add('hidden');
            document.getElementById('authForm').reset();
        }

        // 设置为登录模式
        function setLoginMode() {
            isLoginMode = true;
            document.getElementById('modalTitle').textContent = '用户登录';
            document.getElementById('authSubmitBtn').textContent = '登录';
            document.getElementById('toggleModeBtn').textContent = '没有账号？点击注册';
            document.getElementById('emailGroup').style.display = 'none';
            document.getElementById('fullNameGroup').style.display = 'none';
        }

        // 设置为注册模式
        function setRegisterMode() {
            isLoginMode = false;
            document.getElementById('modalTitle').textContent = '用户注册';
            document.getElementById('authSubmitBtn').textContent = '注册';
            document.getElementById('toggleModeBtn').textContent = '已有账号？点击登录';
            document.getElementById('emailGroup').style.display = 'block';
            document.getElementById('fullNameGroup').style.display = 'block';
        }

        // 切换认证模式
        function toggleAuthMode() {
            if (isLoginMode) {
                setRegisterMode();
            } else {
                setLoginMode();
            }
            document.getElementById('authForm').reset();
        }

        // 处理表单提交
        document.getElementById('authForm').addEventListener('submit', async function(e) {
            e.preventDefault();

            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            if (isLoginMode) {
                await login(username, password);
            } else {
                const email = document.getElementById('email').value;
                const fullName = document.getElementById('fullName').value;
                await register(username, password, email, fullName);
            }
        });

        // 显示登录界面（兼容旧代码）
        function showLogin() {
            showAuthModal();
        }

        // 用户登录
        async function login(username, password) {
            try {
                const response = await fetch('/api/auth/login', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ username, password })
                });

                if (response.ok) {
                    const data = await response.json();
                    localStorage.setItem('access_token', data.access_token);
                    checkLoginStatus();
                    closeAuthModal();
                    alert('登录成功！');
                } else {
                    const error = await response.json();
                    alert(`登录失败: ${error.detail}`);
                }
            } catch (error) {
                alert(`登录错误: ${error.message}`);
            }
        }

        // 用户注册
        async function register(username, password, email, fullName) {
            try {
                const response = await fetch('/api/auth/register', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        username,
                        password,
                        email: email || null,
                        full_name: fullName || null
                    })
                });

                if (response.ok) {
                    alert('注册成功！请登录');
                    setLoginMode();
                    document.getElementById('username').value = username;
                    document.getElementById('password').value = '';
                } else {
                    const error = await response.json();
                    alert(`注册失败: ${error.detail}`);
                }
            } catch (error) {
                alert(`注册错误: ${error.message}`);
            }
        }

        // 用户退出
        function logout() {
            localStorage.removeItem('access_token');
            document.getElementById('userInfo').textContent = '未登录';
            document.getElementById('loginBtn').classList.remove('hidden');
            document.getElementById('logoutBtn').classList.add('hidden');
            alert('已退出登录');
        }

        // 刷新系统状态
        async function refreshStatus() {
            // 检查API状态
            try {
                const response = await fetch('/health');
                document.getElementById('apiStatus').textContent = response.ok ? '✅ 正常' : '❌ 异常';
                document.getElementById('apiStatus').style.color = response.ok ? '#28a745' : '#dc3545';
            } catch {
                document.getElementById('apiStatus').textContent = '❌ 异常';
                document.getElementById('apiStatus').style.color = '#dc3545';
            }

            // 检查实时服务状态
            try {
                const response = await fetch('/api/realtime/status');
                if (response.ok) {
                    const data = await response.json();
                    document.getElementById('redisStatus').textContent = 
                        data.data.redis_status === 'connected' ? '✅ 连接' : '⚠️ 断开';
                    document.getElementById('wsStatus').textContent = 
                        `${data.data.active_connections} 连接`;
                }
            } catch {
                document.getElementById('redisStatus').textContent = '❌ 异常';
                document.getElementById('wsStatus').textContent = '❌ 异常';
            }

            // 检查数据库状态
            try {
                const response = await fetch('/api/stock/stocks');
                document.getElementById('dbStatus').textContent = response.ok ? '✅ 正常' : '❌ 异常';
                document.getElementById('dbStatus').style.color = response.ok ? '#28a745' : '#dc3545';
            } catch {
                document.getElementById('dbStatus').textContent = '❌ 异常';
                document.getElementById('dbStatus').style.color = '#dc3545';
            }
        }

        // 切换实时监控
        function toggleRealtime() {
            const panel = document.getElementById('realtimePanel');
            const toggleBtn = document.getElementById('realtimeToggleBtn');

            if (isRealtimeActive) {
                stopRealtime();
                panel.classList.add('hidden');
                toggleBtn.textContent = '📈 启动实时股价监控';
                toggleBtn.className = 'btn btn-success';
                isRealtimeActive = false;
            } else {
                startRealtime();
                panel.classList.remove('hidden');
                toggleBtn.textContent = '⏹️ 停止实时监控';
                toggleBtn.className = 'btn btn-danger';
                isRealtimeActive = true;
            }
        }

        // 启动实时监控
        function startRealtime() {
            const wsUrl = `ws://localhost:8000/api/realtime/ws`;
            ws = new WebSocket(wsUrl);

            ws.onopen = function() {
                console.log('WebSocket连接已建立');
            };

            ws.onmessage = function(event) {
                const data = JSON.parse(event.data);
                console.log('📨 收到WebSocket消息:', data);

                if (data.type === 'realtime_price') {
                    updateStockDisplay(data.data);
                } else if (data.type === 'subscription_success') {
                    console.log(`✅ 订阅成功: ${data.stock_code}`);
                } else if (data.type === 'unsubscription_success') {
                    console.log(`✅ 取消订阅成功: ${data.stock_code}`);
                } else if (data.type === 'pong') {
                    console.log('🏓 收到pong响应');
                }
            };

            ws.onclose = function() {
                console.log('WebSocket连接已关闭');
            };

            ws.onerror = function(error) {
                console.error('WebSocket错误:', error);
            };
        }

        // 停止实时监控
        function stopRealtime() {
            if (ws) {
                ws.close();
                ws = null;
            }
            monitoredStocks.clear();
            document.getElementById('stockGrid').innerHTML = '';
        }

        // 添加股票监控
        function addStock() {
            const stockCode = document.getElementById('stockInput').value.trim().toUpperCase();
            if (!stockCode) {
                alert('请输入股票代码');
                return;
            }

            // 验证股票代码格式
            if (!/^[0-9]{6}$/.test(stockCode)) {
                alert('请输入6位数字的股票代码');
                return;
            }

            if (monitoredStocks.has(stockCode)) {
                alert('该股票已在监控中');
                return;
            }

            monitoredStocks.add(stockCode);

            // 先创建卡片显示"加载中"
            createStockCard(stockCode);

            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({
                    action: 'subscribe',
                    stock_code: stockCode
                }));
                console.log(`📡 订阅股票: ${stockCode}`);
            } else {
                console.warn('WebSocket未连接，尝试重新连接...');
                startRealtime();
            }

            document.getElementById('stockInput').value = '';
        }

        // 创建股票卡片
        function createStockCard(stockCode) {
            const grid = document.getElementById('stockGrid');

            // 检查是否已存在该卡片
            const existingCard = document.getElementById(`stock-${stockCode}`);
            if (existingCard) {
                console.log(`股票卡片 ${stockCode} 已存在`);
                return;
            }

            const card = document.createElement('div');
            card.className = 'stock-card';
            card.id = `stock-${stockCode}`;
            card.innerHTML = `
                <div class="stock-header">
                    <div class="stock-code">${stockCode}</div>
                    <button class="remove-btn" onclick="removeStock('${stockCode}')" title="移除监控">×</button>
                </div>
                <div class="stock-name">获取名称中...</div>
                <div class="stock-price">加载中...</div>
                <div class="stock-change">等待数据...</div>
                <div class="stock-volume">成交量: --</div>
                <div class="stock-time">更新时间: --</div>
            `;
            grid.appendChild(card);
            console.log(`✅ 创建股票卡片: ${stockCode}`);
        }

        // 更新股票显示
        function updateStockDisplay(data) {
            const card = document.getElementById(`stock-${data.stock_code}`);
            if (!card) {
                console.warn(`未找到股票卡片: ${data.stock_code}`);
                return;
            }

            const changeClass = data.change_percent >= 0 ? 'price-up' : 'price-down';
            const changeSymbol = data.change_percent >= 0 ? '+' : '';
            const currentTime = new Date().toLocaleTimeString();

            card.innerHTML = `
                <div class="stock-header">
                    <div class="stock-code">${data.stock_code}</div>
                    <button class="remove-btn" onclick="removeStock('${data.stock_code}')" title="移除监控">×</button>
                </div>
                <div class="stock-name">${data.stock_name}</div>
                <div class="stock-price ${changeClass}">¥${data.current_price}</div>
                <div class="stock-change ${changeClass}">
                    ${changeSymbol}${data.change_amount} (${changeSymbol}${data.change_percent}%)
                </div>
                <div class="stock-volume">成交量: ${(data.volume / 10000).toFixed(0)}万</div>
                <div class="stock-time">更新: ${currentTime}</div>
            `;

            console.log(`📈 更新股票数据: ${data.stock_code} - ${data.stock_name} - ¥${data.current_price}`);
        }

        // 移除单个股票监控
        function removeStock(stockCode) {
            if (ws && ws.readyState === WebSocket.OPEN) {
                ws.send(JSON.stringify({
                    action: 'unsubscribe',
                    stock_code: stockCode
                }));
            }

            monitoredStocks.delete(stockCode);
            const card = document.getElementById(`stock-${stockCode}`);
            if (card) {
                card.remove();
            }

            console.log(`🗑️ 移除股票监控: ${stockCode}`);
        }

        // 清空股票监控
        function clearStocks() {
            monitoredStocks.forEach(stockCode => {
                if (ws && ws.readyState === WebSocket.OPEN) {
                    ws.send(JSON.stringify({
                        action: 'unsubscribe',
                        stock_code: stockCode
                    }));
                }
            });
            monitoredStocks.clear();
            document.getElementById('stockGrid').innerHTML = '';
            console.log('🗑️ 清空所有股票监控');
        }

        // 快速添加股票
        function quickAddStock(stockCode) {
            document.getElementById('stockInput').value = stockCode;
            addStock();
        }

        // 显示用户管理
        async function showUserManagement() {
            const token = localStorage.getItem('access_token');
            if (!token) {
                alert('请先登录');
                showLogin();
                return;
            }

            // 先检查权限，不显示界面
            try {
                const response = await fetch('/api/auth/users', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.status === 403) {
                    alert('需要管理员权限才能访问用户管理功能');
                    return;
                } else if (!response.ok) {
                    alert('检查权限时发生错误，请稍后重试');
                    return;
                }

                // 权限检查通过，显示用户管理界面
                document.getElementById('userManagementModal').style.display = 'block';

                // 使用已获取的数据显示用户列表
                const users = await response.json();
                displayUserList(users);

                // 更新用户统计
                document.getElementById('userCount').textContent = `总用户数: ${users.length}`;

            } catch (error) {
                alert(`权限检查失败: ${error.message}`);
            }
        }

        // 关闭用户管理界面
        function closeUserManagement() {
            document.getElementById('userManagementModal').style.display = 'none';
        }

        // 重新加载用户列表（用于状态更新后刷新）
        async function loadUserList() {
            try {
                const token = localStorage.getItem('access_token');

                const response = await fetch('/api/auth/users', {
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    const users = await response.json();
                    displayUserList(users);

                    // 更新用户统计
                    document.getElementById('userCount').textContent = `总用户数: ${users.length}`;
                } else {
                    alert('刷新用户列表失败');
                }
            } catch (error) {
                alert(`刷新用户列表错误: ${error.message}`);
            }
        }

        // 显示用户列表
        function displayUserList(users) {
            const tbody = document.getElementById('userTableBody');
            tbody.innerHTML = '';

            users.forEach(user => {
                const row = document.createElement('tr');
                row.innerHTML = `
                    <td>${user.id}</td>
                    <td>${user.username}</td>
                    <td>${user.email || '未设置'}</td>
                    <td>${user.full_name || '未设置'}</td>
                    <td>
                        <span class="status-badge ${user.is_active ? 'status-active' : 'status-inactive'}">
                            ${user.is_active ? '激活' : '禁用'}
                        </span>
                    </td>
                    <td>
                        <span class="status-badge ${user.is_admin ? 'status-admin' : 'status-user'}">
                            ${user.is_admin ? '管理员' : '普通用户'}
                        </span>
                    </td>
                    <td>${new Date(user.created_at).toLocaleDateString()}</td>
                    <td>
                        <button class="btn btn-sm ${user.is_active ? 'btn-warning' : 'btn-success'}"
                                onclick="toggleUserStatus(${user.id})">
                            ${user.is_active ? '禁用' : '激活'}
                        </button>
                        <button class="btn btn-sm btn-danger" onclick="deleteUser(${user.id}, '${user.username}')">
                            删除
                        </button>
                    </td>
                `;
                tbody.appendChild(row);
            });
        }

        // 切换用户状态
        async function toggleUserStatus(userId) {
            try {
                const token = localStorage.getItem('access_token');
                const response = await fetch(`/api/auth/users/${userId}/toggle-status`, {
                    method: 'PUT',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    alert(result.message);
                    loadUserList(); // 重新加载列表
                } else {
                    const error = await response.json();
                    alert(`操作失败: ${error.detail}`);
                }
            } catch (error) {
                alert(`操作错误: ${error.message}`);
            }
        }

        // 删除用户
        async function deleteUser(userId, username) {
            if (!confirm(`确定要删除用户 "${username}" 吗？此操作不可恢复！`)) {
                return;
            }

            try {
                const token = localStorage.getItem('access_token');
                const response = await fetch(`/api/auth/users/${userId}`, {
                    method: 'DELETE',
                    headers: {
                        'Authorization': `Bearer ${token}`
                    }
                });

                if (response.ok) {
                    const result = await response.json();
                    alert(result.message);
                    loadUserList(); // 重新加载列表
                } else {
                    const error = await response.json();
                    alert(`删除失败: ${error.detail}`);
                }
            } catch (error) {
                alert(`删除错误: ${error.message}`);
            }
        }

        // 定期刷新状态
        setInterval(refreshStatus, 30000); // 每30秒刷新一次
    </script>
</body>
</html>
